package com.javasm.util;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.javasm.commons.config.BootProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class AliyunSmsUtil {// 发送短信工具类
    private static Client client;
    private static BootProperties.ValicodeAk valicodeAk;

    @Resource
    public void setValicodeAk(BootProperties bootProperties){// 静态变量赋值 获取配置文件中的配置
        valicodeAk = bootProperties.getValicodeAk();
    }

    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    //封装发送短信方法 sendValicode（）
    public static void sendValicode(String uphone,String code){
        if(client==null){
            try {
                client = createClient(valicodeAk.getKeyid(), valicodeAk.getKeySecret());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(valicodeAk.getSignName())
                .setTemplateCode(valicodeAk.getTemplateCode())
                .setPhoneNumbers(uphone)
                .setTemplateParam("{\"code\":"+code+"}");

        RuntimeOptions runtime = new RuntimeOptions();
        try {
            client.sendSmsWithOptions(sendSmsRequest, runtime);
            log.info("短信发送成功"
            );
        } catch (Exception e) {
            e.printStackTrace();
            log.error("短信发送失败",e);
        }
    }
}
